<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket事例</title>
</head>
<body>

<script type="text/javascript">

    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8899/ws");

        socket.onmessage = function(event) {
            var ta = document.getElementById("txtResponse");
            ta.value = ta.value + "\n" + event.data;
        }

        socket.onopen = function (event) {
            var ta = document.getElementById("txtResponse");
            ta.value = ta.value + "\n" + "连接开启";
        }

        socket.onclose = function (event) {
            var ta = document.getElementById("txtResponse");
            ta.value = ta.value + "\n" + "连接断开";
        }

    } else {
        alert("浏览器不支持 WebSocket ");
    }

    function sendMsg(msg) {
        if(!window.WebSocket) {
            return;
        }

        if(socket.readyState == WebSocket.OPEN) {
            socket.send(msg);
        } else {
            alert("连接断开");
        }
    }

</script>
<form onsubmit="return false;">
    <textarea id="txtResponse" style="width: 400px; height: 300px;"></textarea> <input type="button" value="清空数据"
                                                                                       onclick="document.getElementById('txtResponse').value='';">
    <br>
    <textarea name="message" style="width: 400px; height: 200px;"></textarea> <input type="button" value="发送数据" onclick="sendMsg(this.form.message.value)" />
</form>

</body>
</html>